import { useState } from 'react';
import { useQuery } from '@tanstack/react-query';
import { Card, Input, Button, Table, Modal, Tag, Space, message } from 'antd';
import { SearchOutlined } from '@ant-design/icons';
import { searchCourses } from '../../api/admin';
import type { Course } from '../../types';

export default function SearchPage() {
  const [query, setQuery] = useState('');
  const [selectedCourse, setSelectedCourse] = useState<Course | null>(null);
  const [isDetailModalOpen, setIsDetailModalOpen] = useState(false);

  const { data: courses = [], isLoading } = useQuery({
    queryKey: ['admin', 'searchCourses', query],
    queryFn: () => searchCourses(query),
    enabled: true, // 自动查询，实时搜索
    staleTime: 0, // 禁用缓存，确保实时更新
  });

  const handleViewDetail = (course: Course) => {
    setSelectedCourse(course);
    setIsDetailModalOpen(true);
  };

  // 计算是否开课：选课人数 >= 最大数量的80%
  const isOpenCourse = (course: Course) => {
    if (course.capacity === 0) return false;
    const enrollmentRate = (course.enrolledCount || 0) / course.capacity;
    return enrollmentRate >= 0.8;
  };

  const columns = [
    {
      title: '课程名称',
      dataIndex: 'name',
      key: 'name',
      width: 200,
      render: (text: string, record: Course) => (
        <Button type="link" onClick={() => handleViewDetail(record)} style={{ padding: 0 }}>
          {text}
        </Button>
      ),
    },
    {
      title: '授课教师',
      dataIndex: 'teacherName',
      key: 'teacherName',
      width: 120,
    },
    {
      title: '学分',
      dataIndex: 'credit',
      key: 'credit',
      width: 80,
    },
    {
      title: '选课人数',
      key: 'enrollment',
      width: 120,
      render: (_: any, record: Course) => (
        <span>
          {record.enrolledCount || 0} / {record.capacity || 0}
        </span>
      ),
    },
    {
      title: '开课状态',
      key: 'status',
      width: 100,
      render: (_: any, record: Course) => {
        const isOpen = isOpenCourse(record);
        return (
          <Tag color={isOpen ? 'green' : 'red'}>
            {isOpen ? '已开课' : '未开课'}
          </Tag>
        );
      },
    },
    {
      title: '操作',
      key: 'action',
      width: 100,
      render: (_: any, record: Course) => (
        <Button type="link" size="small" onClick={() => handleViewDetail(record)}>
          查看详情
        </Button>
      ),
    },
  ];

  return (
    <div className="p-4 pb-24">
      <div className="text-2xl font-semibold mb-4">课程查询</div>

      <Card className="mb-4">
        <Input
          placeholder="请输入教师姓名、工号或课程名称（支持关键字模糊搜索）"
          value={query}
          onChange={(e) => setQuery(e.target.value)}
          prefix={<SearchOutlined />}
          allowClear
          size="large"
        />
      </Card>

      <Card>
        <Table
          dataSource={courses}
          columns={columns}
          rowKey="id"
          loading={isLoading}
          pagination={{
            pageSize: 10,
            showSizeChanger: true,
            showTotal: (total) => query.trim() ? `共找到 ${total} 条结果` : `共 ${total} 门课程`,
          }}
          locale={{
            emptyText: query.trim() ? '未找到相关课程，请尝试其他关键词' : '暂无课程',
          }}
        />
      </Card>

      {/* 课程详情Modal */}
      <Modal
        title="课程详情"
        open={isDetailModalOpen}
        onCancel={() => {
          setIsDetailModalOpen(false);
          setSelectedCourse(null);
        }}
        footer={[
          <Button key="close" onClick={() => setIsDetailModalOpen(false)}>
            关闭
          </Button>,
        ]}
        width={600}
      >
        {selectedCourse && (
          <div className="space-y-4 mt-4">
            <div className="flex gap-4">
              <div className="w-20 text-gray-500">课程名称：</div>
              <div className="text-gray-800 font-medium">{selectedCourse.name}</div>
            </div>
            <div className="flex gap-4">
              <div className="w-20 text-gray-500">授课教师：</div>
              <div className="text-gray-800">{selectedCourse.teacherName}</div>
            </div>
            <div className="flex gap-4">
              <div className="w-20 text-gray-500">学分：</div>
              <div className="text-gray-800">{selectedCourse.credit} 学分</div>
            </div>
            <div className="flex gap-4">
              <div className="w-20 text-gray-500">选课人数：</div>
              <div className="text-gray-800">
                <span className="font-medium">{selectedCourse.enrolledCount || 0}</span>
                {' / '}
                <span>{selectedCourse.capacity || 0}</span>
              </div>
            </div>
            <div className="flex gap-4">
              <div className="w-20 text-gray-500">开课状态：</div>
              <div>
                <Tag color={isOpenCourse(selectedCourse) ? 'green' : 'red'} style={{ fontSize: '14px', padding: '4px 12px' }}>
                  {isOpenCourse(selectedCourse) ? '已开课' : '未开课'}
                </Tag>
                {!isOpenCourse(selectedCourse) && (
                  <span className="text-sm text-gray-500 ml-2">
                    （选课人数未达到最大数量的80%）
                  </span>
                )}
              </div>
            </div>
            {selectedCourse.timeSlots && selectedCourse.timeSlots.length > 0 && (
              <div className="flex gap-4">
                <div className="w-20 text-gray-500">上课时间：</div>
                <div className="text-gray-800">
                  {selectedCourse.timeSlots.map((slot, index) => (
                    <div key={index} className="mb-1">
                      周{['', '一', '二', '三', '四', '五', '六', '日'][slot.dayOfWeek]} {slot.start}-{slot.end}
                      {slot.room && ` (${slot.room})`}
                    </div>
                  ))}
                </div>
              </div>
            )}
          </div>
        )}
      </Modal>
    </div>
  );
}

